package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoServer {

    //负责给销售小姐姐拉客的小哥哥
    //只有一个
    ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true){

            //去接客的小姐姐,可以有很多个,clientSocket会给每个客服端都分配一个~
            Socket clientSocket = serverSocket.accept();
            processConnection(clientSocket);


        }
    }
    //根据请求计算相应并返回客服端
    public void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d]客户端上线\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
        //一直读取请求
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()){
            Scanner scanner = new Scanner(inputStream);//从输入流中读取
            PrintWriter printWriter = new PrintWriter(outputStream);//将字节输出流包装下,改为字符输出流
            while (true){
                if(!scanner.hasNext()){
                    //该流读到了结尾,对端关闭了
                    System.out.printf("[%s:%d]客户端断开连接\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
                }
                //1.接受请求
                String request = scanner.next();//进一步可以使用next方法来读取一段字符串的内容
                //2.根据请求计算相应
                String response = process(request);
                //3.将相应发送给客户端
                //相应也是需要带上换行的
                printWriter.println(response);
                System.out.printf("[%s:%d] rep:%s resp:%s\n",clientSocket.getInetAddress().toString(),clientSocket.getPort(),request,response);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭连接
            //clientSocket只是给一个链接服务的,所以需要关闭
            clientSocket.close();
        }

    }
    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
